package com.mlog.njyjy.ndop.msg.relay.listener;

import com.mlog.njyjy.ndop.msg.common.domain.MessageRecord;
import com.mlog.njyjy.ndop.msg.persistence.dao.MessageRecordRepository;
import com.mlog.njyjy.ndop.msg.relay.event.MsgEvent;
import com.mlog.njyjy.ndop.msg.relay.util.CustomDateUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.ZoneId;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * <p>
 * redis缓存消息响应事件
 * </p>
 *
 * @author zyz
 * @version v1.0, 2020/8/6
 */
@Slf4j
@Component
public class RedisAddListener implements SmartApplicationListener {

    @Autowired
    private MessageRecordRepository messageRecordRepository;

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return MsgEvent.class.equals(eventType);
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }

    @Async
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof MsgEvent) {
            MsgEvent msgEvent = (MsgEvent) event;
            log.info(msgEvent.getKey() + " : " + msgEvent.getValue());
            //TODO: insert into mysql with ttl?
            String body = msgEvent.getValue();
            JSONObject jsonbody = JSONUtil.parseObj(body);
            messageRecordRepository.insert(new MessageRecord()
            		.setMsgKey(msgEvent.getKey())
            		.setMsgValue(msgEvent.getValue())
            		.setAbsoluteDataName(jsonbody.getStr("absoluteDataName"))
            		.setDatetime(CustomDateUtil.datetimeParser(jsonbody.getStr("datetime")).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime())
            		.setFileNames(jsonbody.getStr("fileNames"))
            		.setFileSizes(jsonbody.getStr("fileSizes"))
            		.setMsg_id(jsonbody.getStr("ID"))
            		.setResult(jsonbody.getStr("result"))
            		.setTopic(jsonbody.getStr("topic"))
            		.setSource(jsonbody.getStr("source"))
            		.setType(jsonbody.getStr("type"))
            		.setPid(jsonbody.getStr("PID")));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
